from __future__ import absolute_import

import os

from rw.www import RequestHandler, get, post, mount
import tornado.ioloop

from fullsteam import game
from fullsteam import json
from fullsteam import input
from fullsteam import socket


class Viewer(socket.SteamSocket):
    def open(self):
        print "VIEWER WebSocket opened"
        self.last_data = {}
        self.sync_call = tornado.ioloop.PeriodicCallback(self.sync, 100)
        self.sync_call.start()
        game.VIEWER.append(self)

        #if game._lines:
        #    self.write_message({'lines': game.GAME._lines})

    def sync(self):
        new_data = game.GAME.to_jsonable()
        next_data = self.last_data.copy()
        next_data.update(new_data)
        for key, value in new_data.items():
            if self.last_data.get(key) == value:
                del new_data[key]
        if new_data:
            #print 'send data', new_data
            self.write_message(new_data)
            self.last_data = next_data

    def on_json(self, message):
        # print 'viewer message', message
        if 'line_done' in message:
            game.GAME.line_done(message['line_done'] + 1)
        if message.get('gameover') and not game.GAME.gameover:
            game.GAME.over('The End.')

    def on_close(self):
        print "VIEWER WebSocket closed"
        self.sync_call.stop()
        game.VIEWER.remove(self)



class Main(RequestHandler):
    @get('/')
    def index(self):
        self.finish(template="index.html")

    @get('/tiles.js')
    def tiles(self):
        fnames = []
        pic = os.path.abspath('fullsteam/static/pic')
        for dirpath, dirnames, filenames in os.walk(pic):
            print dirpath, dirnames, filenames
            dirpath = dirpath[len(pic):]
            for fname in filenames:
                print fname
                if fname.endswith('.png'):
                    fnames.append((dirpath + '/' + fname).strip('/\\'))
        self['fnames'] = fnames
        self.finish(template='tiles.js')

    mount('/viewer', Viewer)
    mount('/input', input.Input)


